package springbook.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import springbook.model.Result;
import springbook.model.UserInfo;

import static springbook.constant.Constans.USER_SESSION_KEY;

/**
 * 登陆拦截器（设置一个拦截器，但未执行）
 */

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * true-放行   false-拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("目标方法执行前的代码……");
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(USER_SESSION_KEY);
        if(userInfo==null) {
            response.setStatus(401);
            response.getOutputStream().write("nologin".getBytes());
            return false;
        }
        return true;
    }

 /*   @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("目标方法执行后的代码……");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("视图渲染完成后执行的代码");
    }*/
}
